<script lang="ts">
    import {
        write_file,
        set_file_owner,
        type FsProgressEvent,
        FILE_OWNER_TYPE_BOARD_IMAGE,
    } from "$lib/api/fs";
    import { get_user_session } from "$lib/api/user";
    import { request } from "$lib/utils/request";
    import { Modal, Progress } from "@skeletonlabs/skeleton-svelte";
    import { open as dialog_open } from "@tauri-apps/plugin-dialog";
    import type { XYPosition } from "@xyflow/svelte";
    import { FolderOpen, X } from "lucide-svelte";
    import { drawStore } from "../store.svelte";
    import { Channel } from "@tauri-apps/api/core";
    import { create_node } from "$lib/api/board/board_draw";

    interface ModalProps {
        width: number;
        height: number;
        position: XYPosition;
        onClose: () => void;
    }

    let props: ModalProps = $props();

    let filePath = $state("");
    let progress = $state(null as null | number);

    async function choiceFile() {
        const res = await dialog_open({
            title: "选择图片",
            filters: [
                {
                    name: "图片",
                    extensions: ["png", "jpg", "jpeg"],
                },
            ],
        });
        if (Array.isArray(res)) {
            return;
        } else if (res == null) {
            return;
        }
        filePath = res;
    }

    async function createNode() {
        const sessionId = await get_user_session();
        //上传文件
        const onEvent = new Channel<FsProgressEvent>();
        onEvent.onmessage = (ev) => {
            if (ev.total_step > 0) {
                progress = (ev.cur_step / ev.total_step) * 100;
            }
        };
        const res = await request(
            write_file(
                sessionId,
                drawStore.boardInfo?.image_fs_id ?? "",
                filePath,
                onEvent,
            ),
        );
        //创建节点
        await request(
            create_node({
                session_id: sessionId,
                board_id: drawStore.boardInfo?.board_id ?? "",
                draw_id: drawStore.drawId,
                x: props.position.x,
                y: props.position.y,
                w: props.width,
                h: props.height,
                content: {
                    BasicImageContent: {
                        file_id: res.file_id,
                    },
                },
                node_style: {
                    bg_color: "bg-surface-200",
                    border_width: "border-2",
                    border_color: "border-surface-300",
                    font_color: "text-surface-800",
                    layer: 0,
                },
            }),
        );
        //修改文件owner
        await request(
            set_file_owner({
                session_id: sessionId,
                fs_id: drawStore.boardInfo?.image_fs_id ?? "",
                file_id: res.file_id,
                owner_type: FILE_OWNER_TYPE_BOARD_IMAGE,
                owner_id: drawStore.drawId,
            }),
        );
        props.onClose();
    }
</script>

<Modal
    open={true}
    triggerBase="btn preset-tonal"
    contentBase="card bg-surface-200-800 p-4 space-y-4 shadow-xl shadow-surface-500 w-[600px]"
    backdropBase="backdrop-none"
    closeOnEscape={false}
    closeOnInteractOutside={false}
    onOpenChange={(ev) => {
        if (!ev.open) {
            props.onClose();
        }
    }}
>
    {#snippet content()}
        <header class="flex justify-between">
            <h4 class="h4">创建图片节点</h4>
            <button
                type="button"
                class="btn preset-ghost-primary-500"
                onclick={() => props.onClose()}
            >
                <X />
            </button>
        </header>

        <main>
            <div class="flex gap-2 items-center">
                <input
                    class="input flex-1 rounded-none bg-surface-100-900 text-surface-900-100 mb-2"
                    type="text"
                    bind:value={filePath}
                />
                <button
                    type="button"
                    title="选择文件"
                    onclick={() => choiceFile()}><FolderOpen /></button
                >
            </div>
            {#if progress != null}
                <Progress value={progress} max={100} meterBg="bg-primary-500" />
            {/if}
        </main>

        <footer class="flex justify-end gap-4">
            <button
                type="button"
                class="btn preset-tonal"
                onclick={() => props.onClose()}>取消</button
            >
            <button
                type="button"
                class="btn preset-filled-primary-900-100"
                disabled={filePath == ""}
                onclick={() => {
                    createNode();
                }}
            >
                确定
            </button>
        </footer>
    {/snippet}
</Modal>
